﻿using System;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LenderClearingHouse
{
  public partial class AdminScrapping : PageBase
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      tdImportType.Visible = CurrentUser.UserRole != UserRole.InvestorAdmin;
      fieldsetScraping.Visible =
        !(CurrentUser.UserRole == UserRole.InvestorAdmin
        && CurrentUser.SubRole == UserSubRole.SDReo);
      pnlScrape.Visible = CurrentUser.UserRole != UserRole.InvestorAdmin;
      pnlScrapeLvreoAdmin.Visible =
        CurrentUser.UserRole == UserRole.InvestorAdmin
        && CurrentUser.SubRole == UserSubRole.LVReo;

      if (hfNdsCorp.Value != "")
      {
        ProcessNdsCorp(hfNdsCorp.Value);
        hfNdsCorp.Value = "";
      }
      else if (hfPriority.Value != "")
      {
        ProcessPriority(hfPriority.Value);
        hfPriority.Value = "";
      }
      else if (hfRecon.Value != "")
      {
        ProcessRecon(hfRecon.Value);
        hfRecon.Value = "";
      }
      else if (hfLps.Value != "")
      {
        ProcessLps(hfLps.Value);
        hfLps.Value = "";
      }
    }

    private void ProcessLps(string html)
    {
      try
      {
        DataTable table = PageScrapes.scrapeLpsAsap(html);
        ImportDataAccess.BulkCopyOpeningBidApn(table);

        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key", "alert('Page Scraped and Uploaded Successfully');", true);
        btnNewScrape_Click(null, null);
      }
      catch (Exception ex)
      {
        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key",
          string.Format("alert('An Error Occured {0}');", ex.Message), true);
      }      
    }

    private void ProcessPriority(string html)
    {
      try
      {
        ImportDataAccess.BulkCopyOpeningBidApn(PageScrapes.scrapePriorityPosting(html));

        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key", "alert('Page Scraped and Uploaded Successfully');", true);
        btnNewScrape_Click(null, null);
      }
      catch (Exception ex)
      {
        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key",
          string.Format("alert('An Error Occured');", ex.Message), true);
      }
    }

    protected void btnScrape_Click(object sender, EventArgs e)
    {
      pnlScrape.Visible = false;
      DoScrape(listSites.SelectedValue);
    }

    void DoScrape(string scrapeType)
    {
      if (scrapeType == "AS")
      {
        ProcessAssesorInformation();
      }
      else if (scrapeType == "LPS")
      {
        pnlLps.Visible = true;
      }
      else if (scrapeType == "RECON")
      {
        pnlRecon.Visible = true;
      }
      else if (scrapeType == "NdsCorp")
      {
        pnlNdsCorp.Visible = true;
      }
      else if (scrapeType == "PRIOR")
      {
        pnlPriority.Visible = true;
      }
      else if (scrapeType == "ASLVREO")
      {
        ProcessAssesorInformationLvReo();
      }
    }

    private void ProcessRecon(string html)
    {
      try
      {
        DataTable table = PageScrapes.scrapeReconTrust(html);
        ImportDataAccess.BulkCopyOpeningBid(table);

        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key", "alert('Page Scraped and Uploaded Successfully');", true);
        btnNewScrape_Click(null, null);
      }
      catch (Exception ex)
      {
        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key",
          string.Format("alert('An Error Occured');", ex.Message), true);
      }
    }

    private void ProcessAssesorInformationLvReo()
    {
      try
      {
        //(new DataAccess()).ExecuteSQLNonQuery("Delete from LvReo_ParcellAppraisal");
        string[] apns = ImportDataAccess.getApnLVREOMasterlist();
        DataTable table = ImportDataBuilders.ParcellAppraisal(); //Build main Table
        foreach (string apn in apns)
        {
          string url = string.Format(
            @"http://sandgate.co.clark.nv.us/assrrealprop/ParcelDetail.aspx?hdnParcel={0}&hdnInstance=pcl7",
            apn);
          string content = RequestClient.Get(url);

          //DataTable table2 = PageScrapes.LVREOscrapeParcell(content);
          DataTable table2 = PageScrapes.scrapeParcell(content, apn);
          table.Merge(table2);
        }

        ImportDataAccess.BulkCopyLVREOParcellAppraisal(table); //Bulk copy data

        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key",
          string.Format("alert('There are {0} properties scrapped and imported');", table.Rows.Count), true);
        btnNewScrape_Click(null, null);
      }
      catch (Exception ex)
      {
        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key",
          string.Format("alert('An Error Occured');", ex.Message), true);
      }
    }

    private void ProcessAssesorInformation()
    {
      try
      {
        string[] apns = ImportDataAccess.getApnMasterlist();        
        DataTable table = ImportDataBuilders.ParcellAppraisal(); //Build main Table
        foreach (string apn in apns)
        {
          string url = string.Format(
            @"http://sandgate.co.clark.nv.us/assrrealprop/ParcelDetail.aspx?hdnParcel={0}&hdnInstance=pcl7",
            apn);
          string content = RequestClient.Get(url);

          DataTable table2 = PageScrapes.scrapeParcell(content, apn);
          table.Merge(table2);
        }

        ImportDataAccess.BulkCopyParcellAppraisal(table); //Bulk copy data

        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key",
          string.Format("alert('There are {0} properties scrapped and imported');", table.Rows.Count), true);
        btnNewScrape_Click(null, null);
      }
      catch (Exception ex)
      {
        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key",
          string.Format("alert('An Error Occured');", ex.Message), true);
      }
    }

    public void ProcessNdsCorp(string html)
    {
      try
      {
        ImportDataAccess.BulkCopyOpeningBid(PageScrapes.scrapeNdsCorp(html));

        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key", "alert('Page Scraped and Uploaded Successfully');", true);
        btnNewScrape_Click(null, null);
      }
      catch (Exception ex)
      {
        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key",
          string.Format("alert('An Error Occured');", ex.Message), true);
      }
    }

    protected void btnNewScrape_Click(object sender, EventArgs e)
    {
      pnlScrape.Visible = CurrentUser.UserRole != UserRole.InvestorAdmin;
      pnlScrapeLvreoAdmin.Visible =
        CurrentUser.UserRole == UserRole.InvestorAdmin
        && CurrentUser.SubRole == UserSubRole.LVReo;

      pnlNewScrape.Visible = false;
      pnlNdsCorp.Visible = false;
      pnlPriority.Visible = false;
      pnlRecon.Visible = false;
      pnlLps.Visible = false;
      
      pnlCsvFileImport.Visible = true;
    }

    protected void btnImport_Click(object sender, EventArgs e)
    {
      if (upload.UploadedFiles.Count == 0) return;

      string fileName =
        Path.Combine(Server.MapPath(upload.TargetFolder), upload.UploadedFiles[0].GetName());

      try
      {
        if (CurrentUser.UserRole == UserRole.InvestorAdmin)
        {
          if (CurrentUser.SubRole == UserSubRole.LVReo)
          {
            ImportDataAccess.ImportLvReoMasterListCSV(fileName);
            lbDocumentsUploaded.Text = "Csv file imported to LVREO List.";
          }
          else if (CurrentUser.SubRole == UserSubRole.SDReo)
          {
            ImportDataAccess.ImportSdReoMasterListCSV(fileName);
            lbDocumentsUploaded.Text = "Csv file imported to SDREO List.";
          }
        }

        if (rblImportType.SelectedValue == "Master List")
        {
          ImportDataAccess.ImportMasterListCSV(fileName);
          lbDocumentsUploaded.Text = "Csv file imported to Master List.";
        }

        if (rblImportType.SelectedValue == "Working List")
        {
          ImportDataAccess.ImportWorkingListCSV(fileName);
          lbDocumentsUploaded.Text = "Csv file imported to Working List.";
        }

        if (rblImportType.SelectedValue == "NV Legal")
        {
          ImportDataAccess.ImportNevadaLegalCSV(fileName);
          lbDocumentsUploaded.Text = "Csv file imported to Master List.";
        }

        if (rblImportType.SelectedValue == "Title Info")
        {
          ImportDataAccess.ImportTitleInfoCSV(fileName);
          lbDocumentsUploaded.Text = "Matching properties updated";
        }

        if (rblImportType.SelectedValue == "SDREO")
        {
          ImportDataAccess.ImportSdReoMasterListCSV(fileName);
          lbDocumentsUploaded.Text = "Csv file imported to SDREO List.";
        }

        if (rblImportType.SelectedValue == "LVREO")
        {
          ImportDataAccess.ImportLvReoMasterListCSV(fileName);
          lbDocumentsUploaded.Text = "Csv file imported to LVREO List.";
        }
      }
      catch (Exception ex)
      {
        lbDocumentsUploaded.ForeColor = System.Drawing.Color.Red;
        lbDocumentsUploaded.Text = ex.Message;
      }
    }

    protected void btnClearSelected_Click(object sender, EventArgs e)
    {
      string message = "";

      if (listSites.SelectedValue == "LPS")
      {
        ImportDataAccess.ClearLpsAsap();
        message = "LPS Entries have been cleared.";
      }
      else if (listSites.SelectedValue == "RECON")
      {
        ImportDataAccess.ClearReconTrust();
        message = "Recon Trust Entries have been cleared.";
      }
      else if (listSites.SelectedValue == "NdsCorp")
      {
        ImportDataAccess.ClearNdsCorp();
        message = "NdsCorp Entries have been cleared.";
      }
      else if (listSites.SelectedValue == "PRIOR")
      {
        ImportDataAccess.ClearPriorityPosting();
        message = "Priority Posting Entries have been cleared.";
      }
      else
      {
          message = "Please select a site to clear opening bids from.";
      }

      ScriptManager.RegisterStartupScript(this, this.GetType(),
        "key", string.Format("alert('{0}');", message), true);
    }

    protected void btnClearAllBids_Click(object sender, EventArgs e)
    {
      ImportDataAccess.ClearAllBids();
      ImportDataAccess.ClearAllBidsApn();

      ScriptManager.RegisterStartupScript(this, this.GetType(),
        "key", "alert('All Opening Bid Entries have been cleared.');", true);
    }

    protected void btnScrapeNew_Click(object sender, EventArgs e)
    {
      pnlScrape.Visible = false;

      if (listSites.SelectedValue == "AS")
      {
        ProcessAssesorInformationNewOnly();
      }
      else btnScrape_Click(null, null);
    }

    private void ProcessAssesorInformationNewOnly()
    {
      try
      {
        string[] apns = ImportDataAccess.getApnMasterlistNewOnly();
        //string[] apns = new string[] { "177-27-711-055" };
        DataTable table = ImportDataBuilders.ParcellAppraisal(); //Build main Table
        foreach (string apn in apns)
        {
          string url = string.Format(
            @"http://sandgate.co.clark.nv.us/assrrealprop/ParcelDetail.aspx?hdnParcel={0}&hdnInstance=pcl7",
            apn);
          string content = RequestClient.Get(url);

          DataTable table2 = PageScrapes.scrapeParcell(content, apn);
          table.Merge(table2);
        }

        ImportDataAccess.BulkCopyParcellAppraisal(table); //Bulk copy data

        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key",
          string.Format("alert('There are {0} properties scrapped and imported');", table.Rows.Count), true);
        btnNewScrape_Click(null, null);
      }
      catch (Exception ex)
      {
        ScriptManager.RegisterStartupScript(this, this.GetType(),
          "key",
          string.Format("alert('An Error Occured');", ex.Message), true);
      }
    }

    protected void btnScrapeLvreoAdmin_Click(object sender, EventArgs e)
    {
      pnlScrapeLvreoAdmin.Visible = false;
      DoScrape("ASLVREO");
    }
  }
}